package com.jy.novel.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;

/**
 * Created by jihb on 4/14/16.
 */
public class JsonUtils {

    /**
     * json字符串转为java类
     * @param json
     * @param type
     * @param <T>
     * @return
     */
    public static final <T> T parseJson(String json,Class<T> type){
        ObjectMapper mapper = new ObjectMapper();
        T object=null;
        try {
            object = mapper.readValue(json,type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return object;
    }

    /**
     * java类转为json字符串
     * @param object
     * @return
     */
    public static final String toJson(Object object){
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        StringWriter sw = new StringWriter();
        try {
            mapper.writeValue(sw,object);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return sw.toString();
    }
}
